<template>
    <div ref="editorContainer" class="monaco-editor-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as monaco from 'monaco-editor'
import { editor } from 'monaco-editor'

const props = defineProps<{
    modelValue: string
    language?: string
    options?: editor.IStandaloneEditorConstructionOptions
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void
    (e: 'change', value: string): void
}>()

const editorContainer = ref<HTMLElement>()
let editorInstance: editor.IStandaloneCodeEditor | null = null

// 初始化编辑器
onMounted(() => {
    if (editorContainer.value) {
        editorInstance = monaco.editor.create(editorContainer.value, {
            value: props.modelValue,
            language: props.language || 'javascript',
            theme: 'vs-dark',
            automaticLayout: true,
            minimap: { enabled: false },
            scrollBeyondLastLine: false,
            ...props.options
        })

        // 监听内容变化
        editorInstance.onDidChangeModelContent(() => {
            const value = editorInstance?.getValue() || ''
            emit('update:modelValue', value)
            emit('change', value)
        })
    }
})

// 监听值变化
watch(
    () => props.modelValue,
    (newValue) => {
        if (editorInstance && newValue !== editorInstance.getValue()) {
            editorInstance.setValue(newValue)
        }
    }
)

// 销毁编辑器
onBeforeUnmount(() => {
    if (editorInstance) {
        editorInstance.dispose()
    }
})
</script>

<style scoped>
.monaco-editor-container {
    width: 100%;
    height: 100%;
    min-height: 300px;
}
</style> 